#!/usr/bin/perl

package Login;
use strict;
use Data::Dumper;

sub new($)
{
    my $class = shift;
    
    my $self = {};
    $self->{EM_IDS} = [];
    $self->{RECORDS} = {};
    
    bless ($self, $class);
    
    return $self;
}

sub Insert($$$)
{
    my $self = shift;
    my $emid = shift;
    my $datetime = shift;
    
    push @{$self->{EM_IDS}}, "$emid";
    
    my $v_date = substr($datetime, 0, 8);
    $v_date = substr($v_date, 0, 4) . "-" . substr($v_date, 4, 2) . "-" . substr($v_date, 6);
    my $v_time = substr($datetime, 8);
    $v_time = substr($v_time, 0, 2) . ":" . substr($v_time, 2, 2) . ":" . substr($v_time, 4);
    
    push @{$self->{RECORDS}->{$emid}->{$v_date}}, "$v_time";
}

sub GetAllIds($)
{
    my $self = shift;
    
    return sort @{$self->{EM_IDS}};
}

sub GetAllDates($)
{
    my $self = shift;
    my %dates = ();
    
    for my $id (@{$self->{EM_IDS}}) {
        for my $date (keys %{$self->{RECORDS}->{$id}}) {
            $dates{$date} = 1;
        }
    }
    
    return sort keys %dates;
}

sub GetTime($$$)
{
    my $self = shift;
    my $emid = shift;
    my $date = shift;

    return $self->{RECORDS}->{$emid}->{$date} ? 
        "'" . join(" ", @{$self->{RECORDS}->{$emid}->{$date}}) . "'" : "";    
}
    
package main;

use strict;
use Tk;
use Tk::MsgBox;
use Data::Dumper;

my $win = MainWindow->new();

$win->configure(-title => "Convert");

my $frm1 = $win->Frame(-relief => "groove", -borderwidth => 1
                      )->pack(-side => "top", -fill =>"x");
my $lblInput = $frm1->Label(-text => "Input file:", -width => 16
                           )->pack(-side => "left");
my $fileInput = $frm1->Entry(-width => 40, -background => "white",
                           )->pack(-side => "left", -pady => 1, 
                                   -fill => "x", -expand => 1);
my $btnInput = $frm1->Button(-text => "Browse", -command => sub {&BrowseInput;}
                            )->pack(-side => "right", -fill => "x");
							
my $frm2 = $win->Frame(-relief => "groove", -borderwidth => 1
                      )->pack(-side => "top", -fill =>"x");
my $lblSave = $frm2->Label(-text => "Save  to:", -width => 16
                           )->pack(-side => "left");
my $fileSave = $frm2->Entry(-width => 40, -background => "white",
                           )->pack(-side => "left", -pady => 1, 
                                   -fill => "x", -expand => 1);
my $btnInput = $frm2->Button(-text => "Browse", -command => sub {&BrowseSave;}
                            )->pack(-side => "right", -fill => "x");

my $btnOK = $win->Button(-text => "Convert", -command => sub {&DoConvert;}
                        )->pack(-side => "bottom", -fill => "x", -expand => 1);


MainLoop();

sub BrowseInput()
{
    my $filetypes = [ ["Text file", ".txt"] ];
    my $file = $win->getOpenFile(
	    -title => "Select file to convert",
	    -filetypes => [["Text file", ".txt"]],
	    -defaultextension => ".txt");
    
    if ($file) {
        #$fileInput->delete("start", "end");
        $fileInput->insert("end", $file) ;
    }
}

sub BrowseSave()
{
    my $file = $win->getSaveFile(
	    -title => "Save file to",
	    -filetypes => [["CSV file", ".csv"]],
	    -defaultextension => ".csv");
    if ($file) {
        #$fileSave->delete("start", "end");
        $fileSave->insert("end", $file);
    }
}

sub DoConvert()
{
    my $file_in = $fileInput->get;

    open(IFH, $file_in) || Die("File not found: $file_in");
    
    my $login = Login->new();
    
    while (<IFH>) {
        next if (/^#/);
        next if (/^\s*$/);

        s/^\s+//;
        s/\s+$//;
        
        my @fields = split /\t/;
                
        $login->Insert($fields[1], $fields[2]);
                    
    } 
    close(IFH);
    
    my $file_out = $fileSave->get;
    open(OFH, ">$file_out") || Die("Cannot writ to $file_out");
 
    my @allids = $login->GetAllIds();
    my @alldates = $login->GetAllDates();    
    
#    print "@allids\n";
#    print "@alldates\n";
    print OFH "'ID','" . join("','", @alldates) . "'\n";
    for my $emid (@allids) {
        print OFH "'$emid'";
        for my $date (@alldates) {
            print OFH ","  . $login->GetTime($emid, $date);
        }
        print OFH "\n";
    }
    close(OFH);
    
    my $d = $win->MsgBox(-icon => "info", -title => "Convert", 
                         -type => "ok", -default => "ok",
                         -message => "Convert OK");
    $d->Show;
    
}

sub Die($)
{
    my $msg = shift;
    my $d = $win->MsgBox(-icon => "error", -title => "Error", 
                         -type => "ok", -default => "ok",
                         -message => $msg);
    $d->Show;
    exit;
}